package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GenStatUserCheckinDaily() error {
	fName := "CornStatUserCheckin"
	sql := `insert into main.db_stat_user_checkin
(
  stt_date,
  time_1,
  time_2,
  time_3,
  time_4,
  time_5,
  time_6,
  time_7,
  time_8,
  over_time_8
)
select 
date_sub(date(now()),interval 1 day),
sum(if(continuous = 1,1,0)) as time_1,
sum(if(continuous = 2,1,0)) as time_2,
sum(if(continuous = 3,1,0)) as time_3,
sum(if(continuous = 4,1,0)) as time_4,
sum(if(continuous = 5,1,0)) as time_5,
sum(if(continuous = 6,1,0)) as time_6,
sum(if(continuous = 7,1,0)) as time_7,
sum(if(continuous = 8,1,0)) as time_8,
sum(if(continuous > 8,1,0)) as over_time_8
from main.db_user_checkin
`

	o := models_main.StatUserCheckin{}
	err := global.GetR().Where("stt_date = date_sub(date(now()),interval 1 day)").First(&o).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = global.GetX().Exec(sql).Error
	}
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
